<template>
  <div class="tree">
    <div class="search-group" style="padding: 0">
      <div class="input-wrap" style="width: 100%">
        <div class="input-item" style="padding: 0; width: 100%">
          <a-input
            v-model="value"
            @pressEnter="onSearch"
            @change="handleChange"
            :maxLength="15"
            placeholder="请输入机关名称"
          >
            <a-icon class="search-icon" slot="prefix" type="search" />
            <a-button @click="onSearch" slot="suffix" type="primary" class="searchBtn" style="margin-right: 0"
              >搜索</a-button
            >
          </a-input>
        </div>
      </div>
    </div>
    <div id="treeList">
      <a-tree
        show-icon
        :show-line="false"
        :expandedKeys="expandedKeys"
        :tree-data="departTree"
        :defaultExpandParent="true"
        :auto-expand-parent="autoExpandParent"
        :selectedKeys="selectedKeys"
        @select="onSelect"
        @expand="onExpand"
        :replace-fields="replaceFields"
      >
        <a-icon slot="switcherIcon" type="down" />
        <template #title="{ policeAgencyName }">
          <span v-if="policeAgencyName.indexOf(value) > -1">
            {{ policeAgencyName.substr(0, policeAgencyName.indexOf(value)) }}
            <span style="color: #ecf0f1; background: #74b9ff">{{ value }}</span>
            {{ policeAgencyName.substr(policeAgencyName.indexOf(value) + value.length) }}
          </span>
          <span v-else>{{ policeAgencyName }}</span>
        </template>
      </a-tree>
    </div>
  </div>
</template>
<script>
import { getOneFlagTreeList } from '@/api/api'

export default {
  name: 'tree',
  data() {
    return {
      value: '',
      dataList: [],
      expandedKeys: [],
      autoExpandParent: true,
      departTree: [],
      replaceFields: {
        title: 'policeAgencyName',
        key: 'id',
      },

      selectedKeys: [],
    }
  },
  // mounted() {
  //   this.loadTree()
  // },
  mounted() {
    console.log('组组件挂载')
    this.expandedKeys = []
    this.loadTree()
  },
  activated() {
    console.log('激活')
    this.expandedKeys = []
    this.loadTree()
  },
  methods: {
    loadTree() {
      var that = this
      let departTree = []
      getOneFlagTreeList().then((res) => {
        if (res.code == 200) {
          for (let i = 0; i < res.result.length; i++) {
            let temp = res.result[i]
            departTree.push(temp)
          }
          this.departTree = departTree

          // sessionStorage.setItem('policeIdFirst', that.departTree[0].id)
          // this.$store.commit('is_PoliceAgencyId', that.departTree[0])
          // if (that.departTree[0].orgType == 6) {
          //   this.$store.commit('is_Community', that.departTree[0])
          // }
          this.generateList(this.departTree)
          // 默认选中第一个
          let firstSelected = this.departTree[0]
          if (firstSelected) {
            this.selectedKeys = [firstSelected.id]
            this.$store.commit('is_PoliceAgencyId', firstSelected)
            this.$emit('onSelect', this.selectedKeys, firstSelected)
          }
        }
      })
    },
    onSelect(selectedKeys, info) {
      console.log(selectedKeys,info,'点击选中之后')
      // 当切换之后
      if (selectedKeys.length > 0 && selectedKeys[0] !== this.selectedKeys[0]) {
        this.selectedKeys = [...selectedKeys]
      } else {
        // 设置为之前的值
        this.selectedKeys = [this.selectedKeys[0]]
      }
      let infoList = { ...info.node.dataRef, type: null }
      let selectedData = selectedKeys.length ? info.node.dataRef : infoList
      this.$store.commit('is_PoliceAgencyId', selectedData)
      this.$emit('onSelect', this.selectedKeys, selectedData)
    },

    onExpand(selectedKeys, info) {
      this.$emit('onExpand', selectedKeys, info)
    },

    getParentKey(key, tree) {
      let parentKey
      for (let i = 0; i < tree.length; i++) {
        const node = tree[i]
        if (node.children) {
          if (node.children.some((item) => item.id === key)) {
            parentKey = node.id
          } else if (this.getParentKey(key, node.children)) {
            parentKey = this.getParentKey(key, node.children)
          }
        }
      }
      return parentKey
    },

    generateList(tree) {
      for (let i = 0; i < tree.length; i++) {
        const node = tree[i]
        const id = node.id
        const policeAgencyName = node.policeAgencyName
        this.dataList.push({
          id,
          policeAgencyName: policeAgencyName,
        })
        if (node.children) {
          this.generateList(node.children)
        }
      }
    },

    onExpand(keys) {
      this.expandedKeys = keys
      this.autoExpandParent = false
    },

    onSearch() {
      if (!this.value) {
        this.$message.warning('请输入机关名称后进行搜索！')
        this.expandedKeys = [this.departTree[0].id]
        this.autoExpandParent = false

        // 没有值的时候默认选中第一个
        let firstSelected = this.departTree[0]
        if (firstSelected) {
          this.selectedKeys = [firstSelected.id]
          this.$store.commit('is_PoliceAgencyId', firstSelected)
          this.$emit('onSelect', this.selectedKeys, firstSelected)
        }
        return
      }
      const expanded = this.dataList
        .map((item) => {
          if (item.policeAgencyName.indexOf(this.value) > -1) {
            return this.getParentKey(item.id, this.departTree)
          }
          return null
        })
        .filter((item, i, self) => {
          if (item && self.indexOf(item) === i) {
            return item
          }
        })
      this.expandedKeys = expanded
      this.autoExpandParent = true
    },

    handleChange(e) {
      const value = e.target.value
      if (!value) {
        this.expandedKeys = [this.departTree[0].id]
        this.autoExpandParent = false
        // 没有值的时候默认选中第一个
        let firstSelected = this.departTree[0]
        if (firstSelected) {
          this.selectedKeys = [firstSelected.id]
          this.$store.commit('is_PoliceAgencyId', firstSelected)
          this.$emit('onSelect', this.selectedKeys, firstSelected)
        }
      }
    },
  },
}
</script>

<style>
.ant-input-affix-wrapper .ant-input-suffix {
  right: -7 !important;
}
</style>
